import java.util.PriorityQueue;

public class MyTimer {
    private PriorityQueue<Task> priorityQueue= new PriorityQueue();
    private Object locker = new Object();
    public void schedule (Runnable runnable,long after){
        Task task = new Task(runnable,after);
        priorityQueue.offer(task);
    }
    public MyTimer(){
        Thread t = new Thread(()->{
            while(true){
                try{
                    synchronized (locker){
                        while(priorityQueue.isEmpty()){
                            //任务队列为空阻塞
                            locker.wait();
                        }
                        Task mytask = priorityQueue.peek();
                        long curtime = System.currentTimeMillis();
                        if(curtime>=mytask.getTime()){
                            priorityQueue.poll();
                            mytask.runnable.run();
                        }
                        else {
                            locker.wait(mytask.time-curtime);
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            }
        });
        t.start();
    }


}
class Task implements Comparable<Task>{
    public Runnable runnable ;
    public long time ;
    public Task(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(Task o) {
        return (int)(this.time-o.time);
    }
}

